package com.sec.android.app.myfiles.widget.tablet.bottomdetailview;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.format.Formatter;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.feature.CloudMgr;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.cloud.CloudFileRecord;
import com.sec.android.app.myfiles.module.local.file.LocalFileRecord;
import com.sec.android.app.myfiles.module.local.recent.RecentFileRecord;
import com.sec.android.app.myfiles.util.FileDetailUtils;
import com.sec.android.app.myfiles.util.StorageMonitor;
import com.sec.android.app.myfiles.util.UiUtils;

import java.util.ArrayList;

/**
 * Created by jaebae on 2016-10-05.
 */
public class BottomDetailLeftFocusedView extends BottomDetailView {
    private FileRecord mRootRecord;
    private ProgressBar mStorageBar;
    private RelativeLayout mCloudUsageButtonLayout;
    private RelativeLayout mDetailFileTypeLayout;
    private TextView mBlankDetail;

    BottomDetailLeftFocusedView(View parent, Context context) {
        super(parent, context);
    }

    @Override
    protected void initView(View parent) {
        super.initView(parent);
        mStorageBar = (ProgressBar) parent.findViewById(R.id.storage_progress);
        mCloudUsageButtonLayout = (RelativeLayout) parent.findViewById(R.id.cloud_usage_button_layout);
        mDetailFileTypeLayout = (RelativeLayout) parent.findViewById(R.id.bottom_detail_file_type_layout);
        mBlankDetail = (TextView) parent.findViewById(R.id.blank_detail);
        TextView cloudUsageButton = (TextView) parent.findViewById(R.id.cloud_usage_button);

        if (cloudUsageButton != null) {
            cloudUsageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mRootRecord != null && mRootRecord.isRoot()) {
                        UiUtils.showCloudUsage(mContext, mFragment, mRootRecord);
                    }
                }
            });
        }
    }

    @Override
    public void updateView(ArrayList<FileRecord> recordList, AbsMyFilesFragment fragment) {
        clearView();
        mRecordList = new ArrayList<>(recordList);
        mFragment = fragment;
        mRootRecord = mRecordList.get(0);

        if (mRootRecord instanceof LocalFileRecord || mRootRecord instanceof CloudFileRecord) {
            updateViewForLocalCloud();
        } else if (mRootRecord.getStorageType() == FileRecord.StorageType.Blank) {
            updateViewForBlank();
        } else {
            updateViewForCategory();
        }
    }

    @Override
    protected void clearView() {
        super.clearView();
        mStorageBar.setProgress(0);
        setViewInfo(mStorageBar, null);
        setViewInfo(mBlankDetail, null);
    }

    @Override
    protected void setVisibility(int visibility) {
        super.setVisibility(visibility);
        setViewInfo(mStorageBar, null);
        setViewInfo(mCloudUsageButtonLayout, null);
    }

    private void updateViewForLocalCloud() {
        if (mRootRecord.isRoot()) {
            if (AppFeatures.SUPPORT_SD_CARD && StorageMonitor.isSdCardPath(mRootRecord.getFullPath()) && !StorageMonitor.isSdCardMounted()) {
                mStorageBar.setVisibility(View.GONE);
                setViewInfo(mFileName, mRootRecord.getDisplayName(mContext));
                setViewInfo(mFirstTop, mContext.getString(R.string.not_inserted));
            } else {
                mStorageBar.setVisibility(View.VISIBLE);
                if (mRootRecord.getStorageType() == FileRecord.StorageType.Cloud) {
                    mCloudUsageButtonLayout.setVisibility(View.VISIBLE);
                }

                StorageThread thread = new StorageThread();
                thread.setDaemon(true);
                thread.start();

                setViewInfo(mFileName, mRootRecord.getDisplayName(mContext));
                FileDetailUtils.DirInfo dirInfo = new FileDetailUtils.DirInfo();
                FileDetailUtils.getDirInfo(mContext, mRootRecord, dirInfo, false);
                setViewInfo(mFirstTop, UiUtils.makeContainsString(mContext, dirInfo.fileCnt, dirInfo.dirCnt));
            }
        } else {
            boolean onlyFiles = getSelectedRecordType();
            setViewInfo(mFileName, mRootRecord.getName());
            executeTask(mFirstBottom, mFirstTop, onlyFiles);
        }
    }

    private void updateViewForCategory() {
        setViewInfo(mFileName, mRootRecord.getDisplayName(mContext));
        setViewInfo(mFirstTop, UiUtils.makeItemsString(mContext, mFragment.getTotalFileCount()));
        if (!(mRootRecord instanceof RecentFileRecord) && mFragment.getTotalFileCount() != 0) {
            setViewInfo(mFirstBottom, getFormattedSizeString(mFragment.getTotalFileSize()));
        }
    }

    private void updateViewForBlank() {
        setViewInfo(mBlankDetail, mContext.getResources().getString(R.string.select_category_bottom_detail));
    }

    private final Handler mStorageHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                setViewInfo(mFirstBottom, (String) msg.obj);
                int percent = msg.arg1;
                mStorageBar.setProgress(percent);
            }
        }
    };

    private class StorageThread extends Thread {
        @Override
        public void run() {
            long newUsedSize;
            long totalSize = 0;
            long freeSpace = -1;
            if (StorageMonitor.isCloudPath(mRootRecord.getFullPath())) {
                CloudMgr cloudMgr = CloudMgr.getInstance(mContext);
                FileRecord.CloudType cloudType = ((CloudFileRecord) mRootRecord).getCloudType();
                totalSize = cloudMgr.getTotalSize(cloudType);
                newUsedSize = cloudMgr.getUsedSize(cloudType);

                if (totalSize != 0) {
                    ensureSizeView(totalSize, newUsedSize);
                }
            } else {
                int mStorageType = StorageMonitor.getMatchedStorageType(mRootRecord.getFullPath());
                if (StorageMonitor.isStorageMounted(mContext, mStorageType)) {
                    totalSize = StorageMonitor.getStorageSize(mContext, mStorageType);
                    freeSpace = StorageMonitor.getStorageFreeSpace(mContext, mStorageType);
                }

                if (freeSpace != -1 && totalSize != 0) {
                    newUsedSize = totalSize - freeSpace;
                    ensureSizeView(totalSize, newUsedSize);
                }
            }
        }
    }

    private void ensureSizeView(long totalSize, long usedSize) {
        Message msg = Message.obtain();
        msg.what = 0;
        msg.obj = Formatter.formatFileSize(mContext, usedSize) + " / " +
                Formatter.formatFileSize(mContext, totalSize);
        msg.arg1 = (int) (usedSize * 100 / totalSize);
        mStorageHandler.sendMessage(msg);
    }

    @Override
    protected void setThumbnailViewVisibility() {
        if (mRootRecord.getStorageType() == FileRecord.StorageType.Blank) {
            mDetailFileTypeLayout.setVisibility(View.GONE);
        } else {
            mDetailFileTypeLayout.setVisibility(View.VISIBLE);
            setThumbnailViewVisibility(View.VISIBLE, View.GONE, View.GONE, View.GONE, View.GONE);
        }
    }

    @Override
    protected void setThumbnailView() {
        UiUtils.setHomeItemIcon(mContext, mRootRecord, mStorageIcon);
    }

    @Override
    public void refreshChildView() {
        super.refreshChildView();
        setLayoutParams(mStorageBar, R.dimen.bottom_detail_storage_progress_width, R.dimen.bottom_detail_storage_progress_height);
        setTextSize(mBlankDetail, R.dimen.bottom_detail_text_size);
        int topMargin = mContext.getResources().getDimensionPixelSize(R.dimen.bottom_detail_storage_progress_margin_top);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mStorageBar.getLayoutParams();
        layoutParams.setMargins(0, topMargin, 0, topMargin);
        mStorageBar.setLayoutParams(layoutParams);
    }
}
